<?php
/**
 * Created by PhpStorm.
 * User: LuLingFeng
 * Date: 2018/3/1
 * Time: 10:54
 */
namespace App\Http\Admin\Personnel\Models;

use App\Eloquent\Oa\Log\BusinessTrip;
use App\Eloquent\Oa\Log\Leave;
use App\Eloquent\Oa\Log\Overtime;
use App\Http\Admin\Administration\Models\Flow;
use Framework\BaseClass\Http\Admin\Model;

/**
 * 考勤的相关因素模型  如 请假/出差/加班
 * @author LuLingFeng
 * Class AttendanceFactor
 * @package App\Http\Admin\Personnel\Models
 */
class AttendanceFactor extends Model
{
    public function commonList($stat, $where = [], $paging = [], $select = ['*'], $order = ['start_time', 'asc'])
    {
        // 初始化
        $stat = $stat->orderBy($order[0], $order[1])
            ->select($select);

        // 筛选
        $whereClause = '';
        if (!empty($where['oa_contacts_id'])) $whereClause .= " and oa_contacts_id = {$where['oa_contacts_id']}";
        if (!empty($where['oa_department_id'])) $whereClause .= " and oa_department_id = {$where['oa_department_id']}";
        if (!empty($where['oa_company_id'])) $whereClause .= " and oa_company_id = {$where['oa_company_id']}";
        if (!empty($where['start_time']) && !empty($where['end_time'])) {
            $startTime = is_numeric($where['start_time']) ? $where['start_time'] : strtotime($where['start_time']);
            $endTime = is_numeric($where['end_time']) ? $where['end_time'] : strtotime($where['end_time']);
            $whereTime = "(start_time <= {$startTime} and end_time >= {$endTime})";
            $whereTime .= ' or ' . "(start_time >= {$startTime} and end_time <= {$endTime})";
            $whereTime .= ' or ' . "(start_time <= {$startTime} and end_time >= {$startTime})";
            $whereTime .= ' or ' . "(start_time <= {$endTime} and end_time >= {$endTime})";
            $whereClause .= " and ($whereTime)";
        }
        $whereClause = substr($whereClause, 4);
        $stat->whereRaw($whereClause);

        $totalRow = $stat->count();
        // 分页
        if (!empty($paging['page']) && !empty($paging['page_size'])) {
            $stat->forPage($paging['page'], $paging['page_size']);
        }

        $list = $stat->get();
        return [
            'list'        => $list,
            'totalRow'    => $totalRow,
            'pageCurrent' => isset($paging['page']) ? $paging['page'] : 0
        ];
    }

    public function commonStat($stat, $where = [], $group = '', $select = [])
    {
        // 初始化
        $isTotal = false;
        if (empty($select)) {
            $isTotal = true;
            $select = [\DB::raw('count(1) as total')];
        }
        $stat = $stat->select($select)
            ->groupBy($group);

        // 筛选
        $whereClause = '';
        if (!empty($where['oa_contacts_id'])) $whereClause .= " and oa_contacts_id = {$where['oa_contacts_id']}";
        if (!empty($where['oa_department_id'])) $whereClause .= " and oa_department_id = {$where['oa_department_id']}";
        if (!empty($where['oa_company_id'])) $whereClause .= " and oa_company_id = {$where['oa_company_id']}";
        if (!empty($where['start_time']) && !empty($where['end_time'])) {
            $startTime = is_numeric($where['start_time']) ? $where['start_time'] : strtotime($where['start_time']);
            $endTime = is_numeric($where['end_time']) ? $where['end_time'] : strtotime($where['end_time']);
            $whereTime = "(start_time <= {$startTime} and end_time >= {$endTime})";
            $whereTime .= ' or ' . "(start_time >= {$startTime} and end_time <= {$endTime})";
            $whereTime .= ' or ' . "(start_time <= {$startTime} and end_time >= {$startTime})";
            $whereTime .= ' or ' . "(start_time <= {$endTime} and end_time >= {$endTime})";
            $whereClause .= " and ($whereTime)";
        }
        $whereClause = substr($whereClause, 4);
        $stat->whereRaw($whereClause);
        if ($isTotal) {
            $total = $stat->first();
            if (empty($total)) $ret = 0;
            else $ret = $total['total'];
        } else {
            $ret = $stat->get();
        }
        return $ret;
    }

    /**
     * 检查是否在请假
     * @author LuLingFeng
     * @param $contactsId
     * @param $time
     * @return array
     */
    public function checkLeave($contactsId, $time)
    {
        $ret = [
            'is_on' => false,
            'extra' => [],
        ];
        $log = Leave::where('oa_contacts_id', '=', $contactsId)
            ->where('start_time', '<=', $time)
            ->where('end_time', '>=', $time)
            ->first();
        if (!empty($log)) {
            $ret['is_on'] = true;
            $ret['extra'] = array_merge([
                'type_str' => Flow::getLeaveTypeStr($log['type']),
            ], $log->toArray());
        }
        return $ret;
    }

    /**
     * 检查是否在出差
     * @author LuLingFeng
     * @param $contactsId
     * @param $time
     * @return array
     */
    public function checkBusinessTrip($contactsId, $time)
    {
        $ret = [
            'is_on' => false,
            'extra' => [],
        ];
        $log = BusinessTrip::where('oa_contacts_id', '=', $contactsId)
            ->where('start_time', '<=', $time)
            ->where('end_time', '>=', $time)
            ->first();
        if (!empty($log)) {
            $ret['is_on'] = true;
            $ret['extra'] = array_merge([], $log->toArray());
        }
        return $ret;
    }

    /**
     * 检查是否在加班
     * @author LuLingFeng
     * @param $contactsId
     * @param $time
     * @return array
     */
    public function checkOvertime($contactsId, $time)
    {
        $ret = [
            'is_on' => false,
            'extra' => [],
        ];
        $log = BusinessTrip::where('oa_contacts_id', '=', $contactsId)
            ->where('start_time', '<=', $time)
            ->where('end_time', '>=', $time)
            ->first();
        if (!empty($log)) {
            $ret['is_on'] = true;
            $ret['extra'] = array_merge([], $log->toArray());
        }
        return $ret;
    }

    /**
     * 生成请假记录
     * @author LuLingFeng
     * @param $contactsId
     * @param $departmentId
     * @param $companyId
     * @param $data
     * @return int
     */
    public function initLeave($contactsId, $departmentId, $companyId, $data)
    {
        $time = time();
        $data['days'] = floor(($data['end_time'] - $data['start_time']) / 86400);
        $data['hours'] = floor(($data['end_time'] - $data['start_time']) / 3600);
        $data = [
            'oa_contacts_id'   => $contactsId,
            'oa_department_id' => $departmentId,
            'oa_company_id'    => $companyId,
            'type'             => $data['type'],
            'start_time'       => $data['start_time'],
            'end_time'         => $data['end_time'],
            'days'             => $data['days'],
            'hours'            => $data['hours'],
            'reasons'          => $data['reasons'],
            'created_at'       => $time,
            'updated_at'       => $time,
        ];
        return Leave::insertGetId($data);
    }

    /**
     * 生成出差记录
     * @author LuLingFeng
     * @param $contactsId
     * @param $departmentId
     * @param $companyId
     * @param $data
     * @return int
     */
    public function initBusinessTrip($contactsId, $departmentId, $companyId, $data)
    {
        $time = time();
        $data['days'] = floor(($data['end_time'] - $data['start_time']) / 86400);
        $data['hours'] = floor(($data['end_time'] - $data['start_time']) / 3600);
        $data = [
            'oa_contacts_id'   => $contactsId,
            'oa_department_id' => $departmentId,
            'oa_company_id'    => $companyId,
            'destination'      => $data['destination'],
            'start_time'       => $data['start_time'],
            'end_time'         => $data['end_time'],
            'days'             => $data['days'],
            'hours'            => $data['hours'],
            'reasons'          => $data['reasons'],
            'created_at'       => $time,
            'updated_at'       => $time,
        ];
        return BusinessTrip::insertGetId($data);
    }

    /**
     * 生成加班记录
     * @author LuLingFeng
     * @param $contactsId
     * @param $departmentId
     * @param $companyId
     * @param $data
     * @return int
     */
    public function initOvertimeTrip($contactsId, $departmentId, $companyId, $data)
    {
        $time = time();
        $data['days'] = floor(($data['end_time'] - $data['start_time']) / 86400);
        $data['hours'] = floor(($data['end_time'] - $data['start_time']) / 3600);
        $data = [
            'oa_contacts_id'   => $contactsId,
            'oa_department_id' => $departmentId,
            'oa_company_id'    => $companyId,
            'start_time'       => $data['start_time'],
            'end_time'         => $data['end_time'],
            'days'             => $data['days'],
            'hours'            => $data['hours'],
            'workplace'        => $data['workplace'],
            'work_content'     => $data['work_content'],
            'created_at'       => $time,
            'updated_at'       => $time,
        ];
        return Overtime::insertGetId($data);
    }
}